package connection;


import org.junit.Test;


import java.io.InputStream;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


public class Connection {
  //方式一：
  @Test
  public void method1() throws SQLException {
    Driver driver = new com.mysql.jdbc.Driver();
    // new_database是该数据库的名字。后面需要设置时区、字符集等
    String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";  //和5.17版本有所不同
    // 将用户名和密码保存在
    Properties info = new Properties();
    info.setProperty("user", "root");
    info.setProperty("password", "root");
    // 连接
    java.sql.Connection connect = driver.connect(url, info);
    System.out.println(connect);
  }

  // 方式二：继续迭代,通过properties的方式
  @Test
  public void method2() throws Exception {
    //导入properties文件
    Properties config = new Properties();
    ClassLoader classLoader = Connection.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties");
    config.load(resourceAsStream);
    // 通过反射获取Driver实例
    Class<?> driverClass = Class.forName(config.getProperty("Driver"));
    Driver driver = (Driver) driverClass.getDeclaredConstructor().newInstance();
    // 通过驱动获取与数据库的连接
    String url = config.getProperty("url");
    java.sql.Connection connect = driver.connect(url, config);
    System.out.println(connect);
  }

  //  方式三：通过DriverManager替换Driver
  @Test
  public void method3() throws Exception {
    //导入properties文件
    Properties config = new Properties();
    config.load(ClassLoader.getSystemClassLoader().getResourceAsStream("config.properties"));

    Class<?> driverClass = Class.forName(config.getProperty("Driver"));  // 实际上这一步也不用
    // 底层已经做了，所以不需要自己注册了
    // Driver driver = (Driver) driverClass.newInstance();
    // DriverManager.registerDriver(driver);   // 将驱动实例传入DriverManager

    String url = config.getProperty("url");
    java.sql.Connection connect = DriverManager.getConnection(url, config);
    System.out.println(connect);
  }
}
